package io.kimmking.gateway.filters;

import io.kimmking.gateway.ratelimiter.MyRedisRateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Iterator;
import java.util.Map;

/**
 * org.springframework.cloud.gateway.filter.factory.RequestRateLimiterGatewayFilterFactory
 */

@Slf4j
@Component
public class RateLimitFilter implements GlobalFilter, Ordered {

    @Autowired
    private MyRedisRateLimiter myRedisRateLimiter;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String requestPath = exchange.getRequest().getPath().value();

        String routeId = ((Route)exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR)).getId();
        log.info("当前限流检查的接口Path: {},对应的RouteId: {}", requestPath, routeId);

        return myRedisRateLimiter.isAllowed(routeId, requestPath, requestPath)
            .flatMap((response) -> {
                Iterator var4 = response.getHeaders().entrySet().iterator();

                while(var4.hasNext()) {
                    Map.Entry<String, String> header = (Map.Entry)var4.next();
                    exchange.getResponse().getHeaders().add((String)header.getKey(), (String)header.getValue());
                }

                if (response.isAllowed()) {
                    return chain.filter(exchange);
                } else {
                    ServerWebExchangeUtils.setResponseStatus(exchange, HttpStatus.TOO_MANY_REQUESTS);
                    return exchange.getResponse().setComplete();
                }
            });
    }

    /**
     * 考虑到TokenCheckGlobalFilter过滤器的order是10151，所以需要排在该过滤器后面
     * @return
     */
    @Override
    public int getOrder() {
        return 10152;
    }
}
